package com.bjc.netty.c2;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

/**
 * @program: nettypro
 * @description:
 * @author: bjc
 * @create: 2021-09-21 21:10
 */
@Slf4j
public class EventLoopCinet {

    public static void main(String[] args) throws InterruptedException {
        //1.启动类  带有future  promise的类型都是和异步方法配套使用   用来处理结果
        ChannelFuture channelFuture = new Bootstrap()
                //2.添加EventLoop
                .group(new NioEventLoopGroup())
                //3.选择客户端channel 实现
                .channel(NioSocketChannel.class)
                //4.添加处理器
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    //在连接建立后被调用
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StringEncoder());
                    }
                })
                //5.连接到服务器
                //异步非阻塞 main发起了调用 真正执行connect是nio线程
                .connect(new InetSocketAddress("localhost", 8080));

        //阻塞方法 只到连接建立才会进行下面的代码
        // TODO 1.使用sync方法同步处理结果
        /*channelFuture.sync();
        //代表连接对象
        //无阻塞向下获取channel
        Channel channel = channelFuture.channel();
        log.debug("{}", channel);
        //向服务器发送数据
        channel.writeAndFlush("hello,world");*/

        //TODO 2.使用addListener(回调对象) 方法异步处理结果
        channelFuture.addListener(new ChannelFutureListener() {
            //在nio西安城连接建立好之后会调用operationComplete
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                Channel channel = future.channel();
                log.debug("{}", channel);
                channel.writeAndFlush("hello,world");
            }
        });
    }
}
